package com.gusha.service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gusha.dao.FarmOperationDao;
import com.gusha.model.FarmOperation;
import com.gusha.model.SysArea;
import com.gusha.model.SysAssets;
import com.gusha.model.User;

@Service
@Transactional
public class FarmOperationService {
	@Autowired
    private FarmOperationDao farmOperationDao;

    public Page<FarmOperation> findAll(Pageable pageable, FarmOperation farmOperation) {
        @SuppressWarnings("serial")
        Page<FarmOperation> result = farmOperationDao.findAll(new Specification<FarmOperation>() {
            @Override
            public Predicate toPredicate(Root<FarmOperation> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<Predicate>();
                if (farmOperation.getId() != null) {
                    list.add(cb.equal(root.get("id").as(BigInteger.class),farmOperation.getId()));
                }
                if (farmOperation.getUserId() != null) {
                    list.add(cb.equal(root.get("user").as(User.class),farmOperation.getUserId()));
                }
              
                if (farmOperation.getOpType()!=null) {
                    list.add(cb.equal(root.get("opType").as(BigInteger.class),farmOperation.getOpType()));
                }
                if (farmOperation.getOpTime() !=null) {
                    list.add(cb.equal(root.get("opTime").as(Date.class),farmOperation.getOpTime()));
                }
               
                if (farmOperation.getDeliveryNum() != null) {
                    list.add(cb.equal(root.get("deliveryNum").as(BigInteger.class),farmOperation.getDeliveryNum()));
                }
                if (farmOperation.getDeliveryTime() != null) {
                    list.add(cb.equal(root.get("deliveryTime").as(Date.class),farmOperation.getDeliveryTime()));
                }
                if (farmOperation.getShopType() != null) {
                    list.add(cb.equal(root.get("shopType").as(BigInteger.class),farmOperation.getShopType()));
                }
                
                Predicate[] p = new Predicate[list.size()];
                return cb.and(list.toArray(p));
            }
        },pageable);
         return result;
    }
}
